package com.sff.system {
	
	import com.sff.core.sff_internal;
	import com.sff.manager.ResizeManager;
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	public class LayerSystem extends Sprite {
		
		private var _input 	: ResizeManager;		
		private var _output : ResizeManager;
		
		public function LayerSystem(input:ResizeManager) {
			_output = new ResizeManager();
			
			registerInputResizeManager(input);
		}
		
		public function get resizeManager() : ResizeManager {
			return _output;
		}
		
		/**
		 * @param child the display object that will be added to layer
		 * @param keepCurrentPosition keep the same position of child in layer. If false, the child position is (0,0) in layer
		 */
		public function addChildToLayer(child:DisplayObject):void {			
			
			//child position to (0, 0) of stage
			var childToGlobal:Point = child.localToGlobal(new Point());
			
			//layer position to (0, 0) of stage
			var layerToGlobal:Point = this.localToGlobal(new Point());				
			
			//keep current position of child in layer
			var newPoint:Point = new Point(childToGlobal.x - layerToGlobal.x, childToGlobal.y - layerToGlobal.y);
							
			child.x = newPoint.x; 
			child.y = newPoint.y;
				
			addChild(child);
		}
		
		public function removeChildFromLayer(child:DisplayObject):void {			
			if (child && this.contains(child)) {
				removeChild(child);
			}
		}
				
		public function removeChilds() : void {
			while(numChildren > 0 )  {
				removeChildAt( 0 );
			}
		}
		
		public function dispose() : void {
			removeChilds();
			
			if( _input ) {
				_input.removeEventListener( Event.RESIZE, onInputResizeHandler );
				_input = null;
			}			
		}
		
		private function registerInputResizeManager( rm : ResizeManager ) : void {
			_input = rm;
			_input.addEventListener( Event.RESIZE, onInputResizeHandler );
			
			onInputResizeHandler(null);
		}
		
		private function onInputResizeHandler(evt : Event) : void {
			var transform : Rectangle = _input.sff_internal::getTransform();			
			_output.sff_internal::setTransform(transform);
		}			
	}
}
